import errorCode from '@/utils/errorCode'
import store from '@/store/index.js'
import {
  removeLoginState
} from '@/utils/roc.js'

/**
 * 响应拦截
 * @param {Object} http 
 */
module.exports = (vm) => {
  uni.$u.http.interceptors.response.use((res) => {
    const resData = res.data
    const code = resData.code || 200
    const msg = errorCode[code] || resData.message || errorCode['default']
    /* 对响应成功做点什么 可使用async await 做异步操作*/
    if (resData.code === 200) {
      return Promise.resolve(resData)
    } else if (resData.code === 401) {
      uni.$u.toast("无效的会话，或者会话已过期，请重新登录。", 3000)
      setTimeout(() => {
        removeLoginState()
        uni.reLaunch({
          url: '/pages/login/login'
        })
      }, 2000)
      return Promise.reject(resData)
    } else {
      uni.$u.toast(msg)
      return Promise.reject(resData)
    }
  }, (error) => {
    uni.$u.toast('接口连接异常')
    /*  对响应错误做点什么 （statusCode !== 200）*/
    return Promise.reject(error)
  })
}